/**
 * ----------------------------------------------------------------------------
 * Copyright Jens Konopka
 * 
 * Alle Rechte vorbehalten.
 * Licence: Apache 2.0
 * ----------------------------------------------------------------------------
 *
 * created on 05.03.2012 by jk
 */
package de.sql.toolkit;

import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import de.sql.toolkit.manager.ConnectionManager;

/**
 * @author jk
 * 
 */
public final class Resource {

	private static final String MESSAGE_PROPERTIES = "properties.messages";
	private static final String SETTINGS_PROPERTIES = "properties.settings";
	private static Map<String, String> messages = new HashMap<String, String>();
	private static Map<String, String> settings = new HashMap<String, String>();

	/**
	 * Hide public constructor for this util class.<br>
	 */
	private Resource() {
	}

	/**
	 * @param key
	 * @return
	 */
	public static String getMessage(final String key) {
		final String property = messages.get(key);
		if (property == null) {
			messages.put(key, getProperty(MESSAGE_PROPERTIES, key));
			return getMessage(key);
		}
		return property;
	}

	/**
	 * @param key
	 * @return
	 */
	public static String getProperty(final String key) {
		final String property = settings.get(key);
		if (property == null) {
			settings.put(key, getProperty(SETTINGS_PROPERTIES, key));
			return getProperty(key);
		}
		return property;
	}

	/**
	 * @param resource
	 * @param key
	 * @return
	 */
	private static String getProperty(final String resource, final String key) {
		final ResourceBundle bundle = ResourceBundle.getBundle(resource);
		final String value = bundle.getString(key);
		return value;
	}

	/**
	 * @param key
	 * @throws Exception
	 * @return
	 */
	public static String getSqlSpecProp(final String key) throws Exception {
		String value = null;
		try {

			// search first with specify by the current set db
			final String newKey = key + "." + getSqlServer();
			value = getProperty(newKey);

		} catch (final Exception e) {
			e.printStackTrace();
		}

		if (value == null || value.trim().isEmpty()) {
			value = getProperty(key);

			// search at standard
			if (value == null || value.trim().isEmpty()) {
				throw new Exception(String.format("Resource '%s' not found.", key));
			}
		}

		return value;
	}

	/**
	 * @return z.B. mssql / udb / mysql
	 */
	private static String getSqlServer() {
		final String value = getProperty(ConnectionManager.getDriver());
		return value;
	}

}
